package org.adream.account.rest.api;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.adream.account.aop.annotation.MonitorRequest;
import org.adream.account.entity.UserEntity;
import org.adream.account.model.LoginModel;
import org.adream.account.model.ResultModel;
import org.adream.account.model.UserIntegralModel;
import org.adream.account.rest.api.model.Columns;
import org.adream.account.rest.api.model.DataTableRequest;
import org.adream.account.rest.api.model.DataTableResponse;
import org.adream.account.rest.api.model.UserForm;
import org.adream.account.rest.api.model.UserIntegralLogQueryParams;
import org.adream.account.rest.api.model.UserSearchForm;
import org.adream.account.service.ADreamServiceException;
import org.adream.account.service.LoginService;
import org.adream.account.service.UserService;
import org.adream.account.util.Constant;
import org.adream.account.util.DateUtils;
import org.adream.account.util.UserUtil;
import org.adream.account.util.Utils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.JSONPObject;
import com.github.pagehelper.PageInfo;

/**
 * 用户管理
 * @author sl
 *
 */
@RequestMapping("/user/")
@Controller
public class UserApiController {

	private final static Logger logger = LoggerFactory.getLogger(UserApiController.class);

	@Autowired
	private UserService userService;

	@Autowired
	private LoginService loginService;

	@Value("${image.file.path.userpic}")
	private String userPicPath;

	/**
	 * 通过uid查询用户
	 * 
	 * @param uid
	 *            用户id
	 * @return
	 */
	@RequestMapping(value = "queryUserByUid", produces = "application/json;charset=UTF-8")
	@ResponseBody
	public Object queryUserByUid(String uid,String jsonpCallback,HttpServletRequest request) {
		logger.debug("根据uid查询用户");
		ResultModel<?> rlt = null;
		if(StringUtils.isEmpty(uid)) {
			rlt = new ResultModel<String>(ResultModel.ERR_PARAM, "获取失败,请求参数为空", null);
		}
		UserEntity userEntity = userService.queryUserByUid(uid);
		if(userEntity != null) {
			userEntity.setPhone(Utils.replaceXing(userEntity.getPhone(), Constant.THREE, Constant.FOUR));
			userEntity.setEmail(Utils.hideEmail(userEntity.getEmail()));
		}
		rlt = new ResultModel<UserEntity>(ResultModel.SUCCESS, "获取user成功", userEntity);
		if(!StringUtils.isEmpty(jsonpCallback)){
			JSONPObject jo = new JSONPObject(jsonpCallback);
			jo.addParameter(rlt);
			return jo;
		} else{
			return rlt;
		}
	}
	
	/**
	 * 查询当前登录的用户信息
	 * @param jsonpCallback
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "queryUserself", produces = "application/json;charset=UTF-8")
	@ResponseBody
	public Object queryUserself(String jsonpCallback,HttpServletRequest request,HttpServletResponse response) {
		response.setHeader("Access-Control-Allow-Origin", "*");
		logger.debug("查询当前登录的用户信息");
		ResultModel<?> rlt = null;
		String uid = UserUtil.getUidByRequest(request);
		if(StringUtils.isEmpty(uid)) {
			rlt = new ResultModel<String>(ResultModel.ERR_PARAM, "获取失败,请求参数为空", null);
		}
		UserEntity userEntity = userService.queryUserByUid(uid);
		if(userEntity != null) {
			userEntity.setPhone(Utils.replaceXing(userEntity.getPhone(), Constant.THREE, Constant.FOUR));
			userEntity.setEmail(Utils.hideEmail(userEntity.getEmail()));
		}
		rlt = new ResultModel<UserEntity>(ResultModel.SUCCESS, "获取user成功", userEntity);
		if(!StringUtils.isEmpty(jsonpCallback)){
			JSONPObject jo = new JSONPObject(jsonpCallback);
			jo.addParameter(rlt);
			return jo;
		}else{
			return rlt;
		}
	}

	/**
	 * 查询同一删除标志的用户
	 * 
	 * @param dr
	 *            删除标志
	 * @return
	 */
	@RequestMapping(value = "queryUsersByDr", produces = "application/json;charset=UTF-8")
	@ResponseBody
	public ResultModel<List<UserEntity>> queryUsersByDr(Integer dr) {
		if (StringUtils.isEmpty(String.valueOf(dr))) {
			return new ResultModel<List<UserEntity>>(ResultModel.ERR_PARAM, "请求参数有误", null);
		}
		List<UserEntity> users = userService.queryUsersByDr(dr);
		if(Utils.isEmptyCollection(users)) {
			return new ResultModel<List<UserEntity>>(ResultModel.NOT_FOUND_OBJECT, "查询失败,数据不存在", null);
		}
		return new ResultModel<List<UserEntity>>(ResultModel.SUCCESS, "成功获取user", users);
	}

	/**
	 * 检查用户名是否存在
	 * 
	 * @param uname
	 *            用户名
	 * @return
	 */
	@RequestMapping(value = "checkUname", produces = "application/json;charset=UTF-8")
	@ResponseBody
	public ResultModel<?> checkUname(String uname) {
		boolean isExistUname = userService.isExistUname(uname,null);
		return new ResultModel<String>(ResultModel.SUCCESS, "成功", String.valueOf(isExistUname));
	}

	/**
	 * 检查手机是否已经注册
	 * 
	 * @param phone
	 *            手机号码
	 * @return
	 */
	@RequestMapping(value = "checkPhone", produces = "application/json;charset=UTF-8")
	@ResponseBody
	public ResultModel<?> checkPhone(String phone) {
		boolean isExistPhone = userService.isExistPhone(phone);
		return new ResultModel<String>(ResultModel.SUCCESS, "成功", String.valueOf(isExistPhone));
	}
	
	/**
	 * 检查邮箱是否已绑定
	 * @param email 
	 * 				邮箱
	 * @return
	 */
	@RequestMapping(value = "checkEmail", produces = "application/json;charset=UTF-8")
	@ResponseBody
	public ResultModel<?> checkEmail(String email) {
		boolean isExistEmail = userService.isExistEmail(email);
		return new ResultModel<String>(ResultModel.SUCCESS, "成功", String.valueOf(isExistEmail));
	}

	/**
	 * 删除用户(逻辑删除)
	 * 
	 * @param user
	 *            用户
	 * @return
	 */
	@RequestMapping(value = "deleteUser", produces = "application/json;charset=UTF-8")
	@MonitorRequest
	@ResponseBody
	public ResultModel<?> deleteUser(String uid, HttpServletRequest request) {
		if (StringUtils.isEmpty(uid)) {
			return new ResultModel<String>(ResultModel.ERR_PARAM, "请求参数有误", null);
		} 
		UserEntity user = userService.queryUserByDrAndUid(Constant.ONE, uid);
		return userService.deleteUser(user);
	}

	/**
	 * 批量删除User
	 * 
	 * @param uids
	 *            user ids
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "deleteUsers", produces = "application/json;charset=UTF-8", method = RequestMethod.POST)
	@MonitorRequest
	@ResponseBody
	public ResultModel<?> deleteUsers(@RequestBody String[] uids, HttpServletRequest request) {
		if (StringUtils.isEmpty(uids) || uids.length == Constant.ZERO) {
			return new ResultModel<String>(ResultModel.ERR_PARAM, "请求参数有误", null);
		} else {
			for (String uid : uids) {
				deleteUser(uid, request);
			}
			return new ResultModel<String[]>(ResultModel.SUCCESS, "成功删除User", null);
		}
	}

	/**
	 * 更新
	 * @param form	用户表单
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "updateUserLogin", produces = "application/json;charset=UTF-8", method = RequestMethod.POST)
	@ResponseBody
	public ResultModel<?> updateUserLogin(@RequestBody UserForm form, HttpServletRequest request) {
		if(form == null || StringUtils.isEmpty(form.getUid())) {
			logger.warn("更新失败,参数有误:(");
			return new ResultModel<String>(ResultModel.ERR_PARAM, "更新失败,参数有误", null);
		}
		if(!StringUtils.isEmpty(form.getPhone()) && !Utils.verifyPhone(form.getPhone())) {
			return new ResultModel<String>(ResultModel.ERR_PARAM, "更新失败,手机号码格式有误", null);
		}
		if(!StringUtils.isEmpty(form.getEmail()) && !Utils.verifyEmail(form.getEmail())) {
			return new ResultModel<String>(ResultModel.ERR_PARAM, "更新失败,邮箱有误", null);
		}
		try {
			return userService.updateUserLogin(form);
		} catch (ADreamServiceException e) {
			return new ResultModel<String>(ResultModel.ERR_SYS, e.getMessage(), null);
		}
	}

	/**
	 * 管理端 弃用
	 * 根据删除标志,uname,phone,email,分页查询User
	 * 
	 * @param form
	 *            请求表单
	 * @return
	 */
	@RequestMapping(value = "selectBySomeLike", produces = "application/json;charset=UTF-8", method = RequestMethod.POST)
	@ResponseBody
	public ResultModel<?> selectBySomeLike(@RequestBody UserSearchForm form) {
		if (form == null || StringUtils.isEmpty(form.getDr())) {
			return new ResultModel<String>(ResultModel.ERR_PARAM, "查询失败，请求参数有误", null);
		}
		PageInfo<UserEntity> page = userService.selectBySomeLike(form.getDr(), form.getUid(), form.getUname(), 
				form.getPhone(), form.getEmail(),null,null,form.getPageNo(),form.getPageSize(),"");
		return new ResultModel<PageInfo<UserEntity>>(ResultModel.SUCCESS, "成功查询到User", page);
	}

	/**
	 * 修改login的密码 ，盐保持原本不变
	 * 
	 * @param loginModel
	 *            — getPassword() 为空则重置密码为 000000，不为空则修改密码
	 * @return
	 * @author chenhaoyu
	 */
	@RequestMapping(value = "changeUserPwd", produces = "application/json;charset=UTF-8", method = RequestMethod.POST)
	@MonitorRequest
	@ResponseBody
	public ResultModel<?> changeUserPwd(@RequestBody LoginModel loginModel) {
		try {
			if (loginModel == null || StringUtils.isEmpty(loginModel.getUid())) {
				return new ResultModel<String>(ResultModel.NOT_FOUND_OBJECT, "更新失败", null);
			}
			loginService.changeLoginPwdByUid(loginModel);
			return new ResultModel<String>(ResultModel.SUCCESS, ResultModel.SUCCESS_MSG, null);
		} catch (ADreamServiceException e) {
			return new ResultModel<String>(ResultModel.ERR_PARAM, e.getMessage(), null);
		}
	}
	
	/**
	 * 申请梦想主任
	 * @param jsonString  json字符串
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "applyDirector",produces = "application/json;charset=UTF-8")
	@ResponseBody
	public ResultModel<?> applyDirector(@RequestBody String jsonString,HttpServletRequest request) {
		JSONObject jsonObject = JSONObject.parseObject(jsonString);
		String sid = jsonObject.getString("sid"); 
		String authorizationCode = jsonObject.getString("authorizationCode"); 
		if(StringUtils.isEmpty(sid)||StringUtils.isEmpty(sid.trim())
				||StringUtils.isEmpty(authorizationCode)||StringUtils.isEmpty(authorizationCode.trim())) {
			return new ResultModel<String>(ResultModel.ERR_PARAM, ResultModel.ERR_PARAM_MSG, null);
		}
		try {
			return userService.applyDirector(sid.trim(),authorizationCode.trim(),request);
		} catch (ADreamServiceException e) {
			return new ResultModel<String>(ResultModel.ERR_SERVICE, "程序出错", null);
		}
	}
	/**
	 * 账户合并申请
	 * @param jsonString
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "mergeApplication",produces = "application/json;charset=UTF-8")
	@ResponseBody
	public ResultModel<?> mergeApplication(@RequestBody String jsonString,HttpServletRequest request) {
		JSONObject jsonObject = JSONObject.parseObject(jsonString);
		String otherUid = jsonObject.getString("otherUid"); 
		String choose = jsonObject.getString("choose"); 
		 
		if(StringUtils.isEmpty(otherUid)||StringUtils.isEmpty(otherUid.trim())
				||StringUtils.isEmpty(choose)||StringUtils.isEmpty(choose.trim())) {
			return new ResultModel<String>(ResultModel.ERR_PARAM, ResultModel.ERR_PARAM_MSG, null);
		}
		if(!"my".equals(choose.trim())&&!"other".equals(choose.trim())) {
			return new ResultModel<String>(ResultModel.ERR_PARAM, "数据非法", null);
		}
		return userService.mergeApplication(otherUid,choose,request);
	}
	/**
	 * 账号合并信息查询
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "queryMergeInfo",produces = "application/json;charset=UTF-8")
	@ResponseBody
	public ResultModel<?> queryMergeInfo(HttpServletRequest request) {
		String uid = UserUtil.getUidByRequest(request);
		if(StringUtils.isEmpty(uid)) {
			return new ResultModel<String>(ResultModel.ERR_PARAM, "参数出错", null);
		}
		return userService.queryMergeInfo(uid);
	}
	
	/**
	 * 清空用户缓存
	 * @param uid 	user id
	 * @return
	 */
	@RequestMapping(value = "flushUserCache", produces = "application/json;charset=UTF-8")
	@MonitorRequest
	@ResponseBody
	public ResultModel<?> flushUserCache(String uid) {
		if(StringUtils.isEmpty(uid)) {
			logger.warn("清空缓存失败,uid为空:(");
			return new ResultModel<String>(ResultModel.ERR_PARAM, "清空失败,参数为空", null);
		}
		return userService.flushUserCache(uid);
	}
	
	/**
	 * 修改黑名单
	 * @param jsonString
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "changeBlackList", produces = "application/json;charset=UTF-8")
	@MonitorRequest
	@ResponseBody
	public ResultModel<?> changeBlackList(@RequestBody String jsonString,HttpServletRequest request) {
		if(StringUtils.isEmpty(jsonString)||StringUtils.isEmpty(jsonString.trim())) {
			return new ResultModel<String>(ResultModel.ERR_PARAM, "操作失败,参数为空", null);
		}
		JSONObject jsonObject = JSONObject.parseObject(jsonString);
		String uid = jsonObject.getString("uid");
		String isBlack = jsonObject.getString("isBlack");
		
		if(StringUtils.isEmpty(uid)||StringUtils.isEmpty(isBlack)) {
			return new ResultModel<String>(ResultModel.ERR_PARAM, "操作失败,参数为空", null);
		}
		 return userService.changeBlackList(uid,"1".equals(isBlack.trim())?true:false);
	}
	
	/**
	 * dataTable分页查询用户
	 * @param dp
	 * @return
	 */
	@RequestMapping(value = "queryUsers", produces = "application/json;charset=UTF-8")
	@MonitorRequest
	@ResponseBody
	public DataTableResponse<UserEntity> queryUsers(@RequestBody DataTableRequest dp) {
		int pageSize = dp.getLength();
		int currPage = dp.getStart();
		if (pageSize <= 0) {
			pageSize = 10;
		}
		if (currPage <= 0) {
			currPage = 1;
		}else{
			currPage = currPage/pageSize + 1;
		}
		
		List<Columns> columns = dp.getColumns();
		//搜索条件
		String uid = columns.get(1).getSearch().getValue();
		String uname = columns.get(2).getSearch().getValue();
		String realName = columns.get(3).getSearch().getValue();
		String phone = columns.get(4).getSearch().getValue();
		String email = columns.get(5).getSearch().getValue();
		String rleId = columns.get(6).getSearch().getValue();
		
		//排序条件 只有一个条件 时间 cts 下标6 这里固定
		String order = dp.getOrder().get(0).getDir();
		if(StringUtils.isEmpty(order)) {
			order = "desc";
		}else {
			if(!"desc".equals(order)&&!"asc".equals(order)) {
				order = "desc";
			}
		}
		
		//封装进原service逻辑
		PageInfo<UserEntity> pif = userService.selectBySomeLike(1, uid, uname, 
				phone, email,rleId,order,currPage,pageSize,realName);
		
		DataTableResponse<UserEntity> dtr = new DataTableResponse<UserEntity>();
		dtr.setData(pif.getList());
		dtr.setDraw(dp.getDraw());
		dtr.setRecordsFiltered(pif.getTotal());
		dtr.setRecordsTotal(pif.getTotal());
		return dtr;
	}
	
	/**
	 * 管理后台-用户管理-组合分页查询
	 * @param dp
	 * @return
	 */
	@RequestMapping(value = "queryUsersByInfo", produces = "application/json;charset=UTF-8")
	@MonitorRequest
	@ResponseBody
	public DataTableResponse<UserEntity> queryUsersByInfo(@RequestBody DataTableRequest dp) {
		int pageSize = dp.getLength();
		int currPage = dp.getStart();
		pageSize = pageSize <= Constant.ZERO ? Constant.TWO : pageSize;
		currPage = currPage <= Constant.ZERO ? Constant.ONE : currPage/pageSize + 1; 
		List<Columns> columns = dp.getColumns();
		//搜索条件
		String rleId = columns.get(1).getSearch().getValue();
		String info = columns.get(2).getSearch().getValue();
		String startCtsString = columns.get(3).getSearch().getValue();
		String endCtsString = columns.get(4).getSearch().getValue();
		Date startCts = null;
		Date endCts = null;
		if(!StringUtils.isEmpty(startCtsString)) {
			startCts = DateUtils.string2Date(startCtsString, "yyyy-MM-dd HH:mm:ss");
		}
		if(!StringUtils.isEmpty(endCtsString)) {
			endCts = DateUtils.string2Date(endCtsString, "yyyy-MM-dd HH:mm:ss");			
		}
		//排序条件 只有一个条件 时间 cts
		String order = dp.getOrder().get(0).getDir();
		if(StringUtils.isEmpty(order)) {
			order = Constant.SORT_DESC;
		} else if(!Constant.SORT_DESC.equals(order) && !Constant.SORT_ASC.equals(order)) {
			order = Constant.SORT_DESC;			
		}
		//封装进原service逻辑
		PageInfo<UserEntity> pif = userService.selectByInfo(Constant.ONE, rleId, info, startCts, endCts, order, currPage, pageSize);
		DataTableResponse<UserEntity> dtr = new DataTableResponse<UserEntity>();
		dtr.setData(pif.getList());
		dtr.setDraw(dp.getDraw());
		dtr.setRecordsFiltered(pif.getTotal());
		dtr.setRecordsTotal(pif.getTotal());
		return dtr;
	}
	
	/**
	 * 获取认证相关特殊二维码
	 * @param req
	 * @param res
	 * @return
	 */
	@RequestMapping(value="qr", produces="application/json;charset=UTF-8")
	@ResponseBody
	public Map<?,?> getUserQRCode(HttpServletRequest req,HttpServletResponse res){
		try {
			userService.getUserQRCode(req,res);
		} catch (Exception e) {
			logger.warn(e.getMessage(),e);
		}
		return null;
	}
	
	/**
	 * 查询用户积分
	 * @param dp
	 * @return
	 */
	@RequestMapping(value = "queryUserIntegrals", produces = "application/json;charset=UTF-8")
	@MonitorRequest
	@ResponseBody
	public DataTableResponse<UserIntegralModel> queryUserIntegrals(@RequestBody DataTableRequest dp) {
		List<Columns> columns = dp.getColumns();
		//搜索条件
		String uid = columns.get(0).getSearch().getValue();
		String uname = columns.get(1).getSearch().getValue();
		String realName = columns.get(2).getSearch().getValue();
		String phone = columns.get(3).getSearch().getValue();
		String sname = columns.get(4).getSearch().getValue();
		//后台管理 多个角色id以,隔开
		String rleIdsString = columns.get(5).getSearch().getValue();
		List<String> rleIds = new ArrayList<>();
		if(!StringUtils.isEmpty(rleIdsString)) {
			Arrays.asList(rleIdsString.split(",")).forEach(rleId -> {
				rleIds.add(rleId);
			});
		}
		PageInfo<UserIntegralModel> pageInfo = userService.queryUserIntegralsBySomeFields(uid, uname, realName, phone, sname, rleIds, Constant.ONE, dp.getStart(), dp.getLength());
		DataTableResponse<UserIntegralModel> dtr = new DataTableResponse<UserIntegralModel>();
		dtr.setData(pageInfo.getList());
		dtr.setDraw(dp.getDraw());
		dtr.setRecordsFiltered(pageInfo.getTotal());
		return dtr;
	}
	/**
	 * 	查询用户积分流水
	 * @param dp
	 * @return
	 */
	@RequestMapping(value = "queryUserIntegralLogs", produces = "application/json;charset=UTF-8")
	@MonitorRequest
	@ResponseBody
	public DataTableResponse<UserIntegralModel> queryUserIntegralLogs(@RequestBody DataTableRequest dp) {
		List<Columns> columns = dp.getColumns();
		//搜索条件
		String uid = columns.get(1).getSearch().getValue();
		String uname = columns.get(2).getSearch().getValue();
		String realName = columns.get(3).getSearch().getValue();
		String sname = columns.get(4).getSearch().getValue();
		//后台管理 多个角色id以,隔开
		String rleIdsString = columns.get(5).getSearch().getValue();
		List<String> rleIds = new ArrayList<>();
		if(!StringUtils.isEmpty(rleIdsString)) {
			Arrays.asList(rleIdsString.split(",")).forEach(rleId -> {
				rleIds.add(rleId);
			});
		}
		
		String typeString = columns.get(6).getSearch().getValue();
		List<String> types = new ArrayList<>();
		if(!StringUtils.isEmpty(typeString)) {
			Arrays.asList(typeString.split(",")).forEach(type -> {
				types.add(type);
			});
		}
		
		String startTime = columns.get(0).getSearch().getValue();
		String endTime = columns.get(7).getSearch().getValue();
				
		
		PageInfo<UserIntegralModel> pageInfo = userService.queryUserIntegralLogs(uid, uname, realName, sname, rleIds,types,startTime,endTime, dp.getStart(), dp.getLength());
		DataTableResponse<UserIntegralModel> dtr = new DataTableResponse<UserIntegralModel>();
		dtr.setData(pageInfo.getList());
		dtr.setDraw(dp.getDraw());
		dtr.setRecordsFiltered(pageInfo.getTotal());
		return dtr;
	}
	
	@RequestMapping(value = "exportUpdateUserIntegralLogsExcel", produces = "application/json;charset=UTF-8", method = RequestMethod.POST)
	public void exportUpdateUserIntegralLogsExcel(UserIntegralLogQueryParams queryParams,HttpServletResponse response) {
		try {
			userService.exportUpdateUserIntegralLogsExcel(queryParams,response);
		} catch (Exception e) {
			logger.error("导出失败");
		}
	}
	/**
	 * 更新用户积分数
	 * @param userIntegral
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "updateUserIntegral", produces = "application/json;charset=UTF-8", method = RequestMethod.POST)
	@MonitorRequest
	@ResponseBody
	public ResultModel<?> updateUserIntegral(@RequestBody UserIntegralModel userIntegral, HttpServletRequest request) {
		String uid = UserUtil.getUidByRequest(request);
		if(StringUtils.isEmpty(uid)) {
			logger.warn("更新用户积分数失败,当前用户登录失效:(");
			return new ResultModel<String>(ResultModel.ERR_PARAM, "登录失效,请重新登录", null);
		}
		if((userIntegral.getIntegral() == null ? 0 : userIntegral.getIntegral()) + userIntegral.getIncreaseIntegral() < 0) {
			logger.warn("更新用户积分数失败,积分数小于0");
			return new ResultModel<String>(ResultModel.ERR_PARAM, "更新失败,积分数小于0", null);
		}
		if(StringUtils.isEmpty(userIntegral.getComment()) || StringUtils.isEmpty(userIntegral.getComment().trim())) {
			logger.warn("更新用户积分数失败,备注信息为空:(");
			return new ResultModel<String>(ResultModel.ERR_PARAM, "更新失败,请填写备注信息", null);
		}
		if(userIntegral.getComment().length() > Constant.LONG_DATA_LENGTH) {
			logger.warn("更新用户积分数失败,备注信息太长:(");
			return new ResultModel<String>(ResultModel.WARN_DATA_LENGTH, "备注信息太长,请精简", null);
		}
		return userService.updateUserIntegral(userIntegral);
	}
	
	/**
	 * 导出批量增减积分模板
	 * @param response
	 */
	@RequestMapping(value = "exportUpdateUserIntegralsExcel", produces = "application/json;charset=UTF-8", method = RequestMethod.POST)
	public void exportUpdateUserIntegralsExcel(HttpServletResponse response) {
		userService.exportUpdateUserIntegralsExcel(response);
	}
	
	/**
	 * 批量增加用户积分
	 * @param file
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "importUpdateUserIntegrals", produces = "application/json;charset=UTF-8", method = RequestMethod.POST)
	@MonitorRequest
	@ResponseBody
	public ResultModel<?> importUpdateUserIntegrals(MultipartFile file, HttpServletRequest request) {
		if(file == null) {
			logger.warn("批量增减积分失败,文件为空:(");
			return new ResultModel<String>(ResultModel.ERR_PARAM, "文件不存在,请上传文件", null);
		}
		String uid = UserUtil.getUidByRequest(request);
		if(StringUtils.isEmpty(uid)) {
			logger.warn("批量增减积分失败,uid为空:(");
			return new ResultModel<String>(ResultModel.ERR_PARAM, "登录信息失效,请重新登录", null);
		}
		try {
			return userService.importUpdateUserIntegrals(file);
		} catch (Exception e) {
			logger.warn(e.getMessage());
			return new ResultModel<String>(ResultModel.ERR_PARAM, e.getMessage(), null);
		}
	}
	
	/**
	 * 获取用户积分历史
	 * @param dp
	 * @param request
	 * @return
	 */
	@RequestMapping(value="getIntegralHistory",produces = "application/json;charset=UTF-8")
	@ResponseBody
	public DataTableResponse<Map<String,Object>> getIntegralHistory(@RequestBody DataTableRequest dp,HttpServletRequest request) {
			String uid = UserUtil.getUidByRequest(request);
		
			int pageNo = dp.getStart()/dp.getLength()+1;
			int pageSize = dp.getLength();
			//封装进原service逻辑
			PageInfo<Map<String,Object>> pif = userService.getIntegralHistory(uid,pageNo,pageSize);
			
			DataTableResponse<Map<String,Object>> dtr = new DataTableResponse<Map<String,Object>>();
			dtr.setData(pif.getList());
			dtr.setDraw(dp.getDraw());
			dtr.setRecordsFiltered(pif.getTotal());
			dtr.setRecordsTotal(pif.getTotal());
			return dtr;
	}
	
	/**
	 * 查询我的当前积分
	 * @param request
	 * @return
	 */
	@RequestMapping(value="queryMyIntegral",produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
	@ResponseBody
	public  ResultModel<?> queryMyIntegral(HttpServletRequest request) {
			String uid = UserUtil.getUidByRequest(request);
			if(StringUtils.isEmpty(uid)) {
				return new ResultModel<Integer>(ResultModel.ERR_USER_INFO, ResultModel.ERR_USER_INFO_MSG, 0);
			}
			Integer integral = userService.queryMyIntegralByUid(uid);
			Integer maxIntegral = userService.queryMaxIntegralByUid(uid);
			if(integral == null) {
				integral = 0;
			}
			if(maxIntegral == null) {
				maxIntegral = 0;
			}
			Map<String, Integer> rlt = new HashMap<String, Integer>();
			rlt.put("integral", integral);
			rlt.put("maxIntegral", maxIntegral);
			return new ResultModel<Map<String, Integer>>(ResultModel.SUCCESS, ResultModel.SUCCESS_MSG, rlt);
	}
}